package com.djl.util;

import com.djl.handler.DefaultHandler;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.FactoryBean;
import org.springframework.beans.factory.config.BeanFactoryPostProcessor;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;

import java.lang.reflect.Proxy;

/**
 * 通过FactoryBean工厂的特性
 * @Component 此注解可加可不加,只是借用此类做代理类的创建
 */
@Component
public class MyFactoryBean implements FactoryBean, BeanFactoryPostProcessor {

    private Class type;
    private BeanFactory beanFactory;

    //重点：生成我们需要的代理对象
    @Override
    public Object getObject() throws Exception {
        return Proxy.newProxyInstance(getObjectType().getClassLoader(), new Class[]{getObjectType()},
                new DefaultHandler(beanFactory));
    }

    @Override
    public Class<?> getObjectType() {
        return getType();
    }

    public Class getType() {
        return type;
    }

    public void setType(Class type) {
        this.type = type;
    }

    @Override
    public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
        this.beanFactory = beanFactory;
    }
}
